<?php

namespace App\Trip\Orders;


use App\Models\Orders\Repositories\Interfaces\OrdersInterface;
use App\Models\Orders\Repositories\Interfaces\OrdersRepositoryInterface;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

/**
 *用户最后一次下单成功的订单  已支付成功为 维度
 */
class UserLastOrder
{
    /**
     * 用户最后一笔订单 的乘客数据
     * @param string $user_id
     * @return array
     */
    public static function getLastOrderPassengersIds(string $user_id): array
    {
        return UserLastOrder::getLastOrder($user_id)?->getPassengers()->pluck('passenger_id')->toArray() ?: [];
    }

    public static function getLastOrder(string $user_id): ?OrdersInterface
    {
        $cache_key  = "user:last_order:{$user_id}";
        $last_order = Cache::get($cache_key) ?: null;
        if (!$last_order) {
            // 从orders 里查询
            $query_key = "query:last_order:{$user_id}";
            if (Redis::set($query_key, 1, 'nx', 'ex', 10)) {
                $orderRepo  = app(OrdersRepositoryInterface::class);
                $last_order = $orderRepo->lastOrder($user_id);
                $last_order && self::setLastOrder($last_order);
            }
        }
        return $last_order;
    }

    public static function setLastOrder(OrdersInterface $order): void
    {
        $cache_key = "user:last_order:{$order->getUserId()}";
        Cache::put($cache_key, $order, config('trip.ttl.year'));
    }
}